package supercafe.core;

import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MenuItemsScreen2 extends ListActivity implements OnClickListener{
   
	private ListView listView;
	private TextView tvSelectedItems;
    
    private ArrayList<MenuItem> listMenuItems = null;
    private MenuType menuType = null;
    private ArrayList<Integer> selectedItemIDs = null;
    private MenuItemAdapter m_adapter;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_items_screen);
        
        //init listview
        listView = this.getListView();
        listView.setItemsCanFocus(false);
        //init text view selected items
        tvSelectedItems = (TextView) findViewById(R.id.tvSelections);
        tvSelectedItems.setText("Chạm để chọn món...");
        
        //get intent bundle
        //Bundle receivedBundle = getIntent().getExtras();
        //menuType = receivedBundle.getParcelable("listMenuItems");
        menuType = (MenuType)getIntent().getParcelableExtra("menu");
        //String title = receivedBundle.getString("title");
        //final int typeId = receivedBundle.getInt("typeId");
        
        String title = menuType.getTypeName();
        
        //get child view
        TextView tvTitle = (TextView) findViewById(R.id.menuTitle);
        tvTitle.setText(title);
        
        Button btnCancel = (Button) findViewById(R.id.btnCancelMenu);
        btnCancel.setOnClickListener(this);
        Button btnSummit = (Button) findViewById(R.id.btnSubmitMenu);
        btnSummit.setOnClickListener(this);
        
        listMenuItems = (ArrayList<MenuItem>) menuType.getMenuItems();        
        this.m_adapter = new MenuItemAdapter(this, R.layout.list_menu_items_row, listMenuItems);
        setListAdapter(this.m_adapter);
    }
        
    private class MenuItemAdapter extends ArrayAdapter<MenuItem> implements OnCheckedChangeListener {

        private ArrayList<MenuItem> listMenuItems;
        private int layoutId;
        private LayoutInflater mInflater;
        private Context context;
        
		public MenuItemAdapter(Context context, int textViewResourceId, ArrayList<MenuItem> items) {
            super(context, textViewResourceId, items);
            this.listMenuItems = items;
            mInflater = LayoutInflater.from(context);
            this.layoutId = textViewResourceId;
            this.context = context;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    v = mInflater.inflate(layoutId, null);
                }
                final MenuItem o = listMenuItems.get(position);
                if (o != null) {
                	final TextView tvMenuItemName = (TextView) v.findViewById(R.id.menuItemName);
                	final TextView tvMenuItemPrice = (TextView) v.findViewById(R.id.menuItemPrice);
                	final CheckBox cbSelected = (CheckBox) v.findViewById(R.id.menuItemChecked);
                    
                    if (tvMenuItemName != null) {
	                	tvMenuItemName.setText(o.getMenuItemName());   
	            		
	                }
	                if (tvMenuItemPrice != null) {
	                	tvMenuItemPrice.setText(""+o.getMenuItemPrice());   
	                }
	                
	                if (cbSelected != null) {
	                	cbSelected.setOnCheckedChangeListener(this);
	                }
	            }
                return v;
        }
        
        @Override
    	public boolean hasStableIds() {
    		return true;
    	}
        
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			showSelectedItems();
		}
		
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return listMenuItems.get(position).getMenuItemId();
		}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==R.id.btnSubmitMenu){
			executeDone();
		}
		else if(v.getId()==R.id.btnCancelMenu){
			setResult(Activity.RESULT_CANCELED);
	        finish();
		}
	}

    private void executeDone() {
    	
    	getSelectedItemIds();
    	
    	if(selectedItemIDs==null || selectedItemIDs.isEmpty()) return;
    	
        Intent resultIntent = new Intent();
        resultIntent.putExtra("menuTypeId", menuType.getTypeId());
        resultIntent.putExtra("itemIDs", selectedItemIDs);
        
        setResult(Activity.RESULT_OK, resultIntent);
        finish();
    }
    
    private void showSelectedItems() {
		// Get an array that tells us for each position whether the item is
		// checked or not
		// --
		SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
		if (checkedItems == null) {
			tvSelectedItems.setText("Chạm để chọn món...");
			return;
		}
		StringBuffer sb = new StringBuffer("Bạn đã chọn: ");
		// For each element in the status array
		// --
		boolean isFirstSelected = true;
		int checkedItemsCount = checkedItems.size();
		for (int i = 0; i < checkedItemsCount; ++i) {
			// This tells us the item position we are looking at
			// --
			final int position = checkedItems.keyAt(i);

			// This tells us the item status at the above position
			// --
			final boolean isChecked = checkedItems.valueAt(i);

			if (isChecked) {
				if (!isFirstSelected) {
					sb.append(", ");
				}
				sb.append(this.listMenuItems.get(position).getMenuItemName());
				isFirstSelected = false;
			}
		}

		// Show a message with the countries that are selected
		// --
		//Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
		tvSelectedItems.setText(sb);
	}
    
    private void getSelectedItemIds() {
    	this.selectedItemIDs = new ArrayList<Integer>();
		// Get an array that tells us for each position whether the item is
		// checked or not
		// --
		SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
		if (checkedItems == null) {
			tvSelectedItems.setText("Chạm để chọn món...");
			//Toast.makeText(this, "No selection info available",Toast.LENGTH_LONG).show();
			return;
		}
		StringBuffer sb = new StringBuffer("Bạn đã chọn: ");
		// For each element in the status array
		// --
		boolean isFirstSelected = true;
		int checkedItemsCount = checkedItems.size();
		for (int i = 0; i < checkedItemsCount; ++i) {
			// This tells us the item position we are looking at
			// --
			final int position = checkedItems.keyAt(i);

			// This tells us the item status at the above position
			// --
			final boolean isChecked = checkedItems.valueAt(i);

			if (isChecked) {
				if (!isFirstSelected) {
					sb.append(", ");
				}
				selectedItemIDs.add(this.listMenuItems.get(position).getMenuItemId());
				sb.append(""+this.listMenuItems.get(position).getMenuItemId());
				isFirstSelected = false;
			}
		}
		
		String tmpStr = new String();
		for(int i=0;i<selectedItemIDs.size();i++)
			tmpStr += " , "+ selectedItemIDs.get(i);
		// Show a message with the countries that are selected
		// --
		//Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
		//Toast.makeText(this, tmpStr, Toast.LENGTH_LONG).show();
	}
}